package com.trainfinder.ripper;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.xpath.XPath;

import com.trainfinder.datapersistace.TicketType;
import com.trainfinder.requestor.ExtractValues;
import com.trainfinder.requestor.UnparsableException;

class ExtractStandardTicketValuesImpl extends AbstractParser implements
		ExtractValues {

	private static final String XPATH_STR = "/xhtml:html/xhtml:body/xhtml:div/"
			+ "xhtml:div[@id='center_01']/xhtml:form/"
			+ "xhtml:div[@id='calendar']/xhtml:table/" + "xhtml:tbody/xhtml:tr";

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.trainfinder.ripper.ExtractValues#getValues(java.io.ByteArrayInputStream)
	 */
	public String[] getValues(InputStream inputStream)
			throws UnparsableException {

		String[] result;
		SAXBuilder saxBuilder = new SAXBuilder(
				"org.apache.xerces.parsers.SAXParser");

		final Document jdomDocument;
		try {

			jdomDocument = saxBuilder.build(inputStream);

			int columnCount = getColumnCount(jdomDocument);
			Ticket[] tickets = getTickets(jdomDocument, columnCount);

			result = getValues(jdomDocument, tickets, columnCount, XPATH_STR
				 );

		} catch (JDOMException e) {
			throw new UnparsableException(e);
		} catch (IOException e) {
			throw new UnparsableException(e);
		}
		return result;

	}

	private String[] getValues(Document jdomDocument, Ticket[] tickets,
			int columnCount, String xPath) throws UnparsableException {
		int i = 0;

		Collection<String> result = new ArrayList<String>();
		
		int rowCount = getRowCount(jdomDocument);
		
		for (int column = 4; column <= columnCount; column++) {

			if (tickets[i].getTicketClass() == TicketClass.Standard
					&& tickets[i].getTicketType() != TicketType.FULLY_FLEXIBLE) {

				String data = null;
				int row = 1;
				while (  row <= rowCount) {
					String rowPath = xPath + "[" + row + "]";

					String inputXPath = rowPath + "/xhtml:td[" + column
							+ "]/xhtml:input";

					data = getAttributeValueFromNode(inputXPath, jdomDocument);
					result.add(data);
				
					if (data != null) { 
						break;
					}
					row++;
					
				}
				 
			}
			i++;

		}
		return (String[]) result.toArray(new String[result.size()]);

	}

	public String getAttributeValueFromNode(String xPathStr,
			Document jdomDocument) throws UnparsableException {

		String result = "";

		try {
			Element e;
			XPath xp = XPath.newInstance(xPathStr);
			xp.addNamespace(NS);
			e = (Element) xp.selectSingleNode(jdomDocument);
			result = e.getAttributeValue("value").trim();
		} catch (NullPointerException e) {
			return null;
		} catch (JDOMException e) {
			return null;
		} catch (Exception e) {
			return null;
		}

		return result;
	}

}
